package com.smartwebx.fr.service.ckeditor;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.aspectj.weaver.patterns.ParserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.smartwebx.fr.bean.mysql.Page;
import com.smartwebx.fr.bean.mysql.PageFreetable;
import com.smartwebx.fr.dao.mysql.PageFreetableMapper;
import com.smartwebx.fr.dao.mysql.PageMapper;
import com.smartwebx.fr.dao.mysql.PagePointMapper;
import com.smartwebx.fr.util.StationFinalFields;

@Service
@Transactional
public class PageService {
	@Autowired
	private PageMapper pageDao;
	@Autowired
	private PageFreetableMapper pageFreeTableDao;
	@Autowired
	private PagePointMapper pagePointDao;

	public void saveReport(Integer pageId, String pageHtml, Integer ckWidth,
			Integer ckHeight, List<PageFreetable> pageFreeTables,
			Set<String> pointIdSet) {
		String decodeData = null;
		try {
			decodeData = URLDecoder.decode(pageHtml,
					StationFinalFields.DEFAULT_ENCODE);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Page page = pageDao.selectByPrimaryKey(pageId);
		page.setPageId(pageId);
		page.setPageText(decodeData);
		page.setCkHeight(ckHeight);

		pageDao.updateByPrimaryKeySelective(page);

		pageFreeTableDao.removeByPageId(pageId);
		for (PageFreetable free : pageFreeTables) {
			pageFreeTableDao.insert(free);
		}
		List<String> dbPointIdList = pagePointDao.getPointsByPageId(pageId);
		// 更新 page_point
		Set<String> dbPoints = Sets.newHashSet(dbPointIdList);
		// 差集，找到数据库里有，而界面没有的id
		Set<String> lostDbPoints = Sets.difference(dbPoints, pointIdSet);
		for (String pointId : lostDbPoints) {
			pagePointDao.deleteByPrimaryKey(pointId);
		}
	}

	public void savePageName(Integer pageId,Boolean remberParam, String pageTitle) {
		Page page = new Page();
		page.setPageTitle(pageTitle);
		page.setPageId(pageId);
		pageDao.updateByPrimaryKeySelective(page);
	}


	/**
	 * 获得 PageBean
	 * 
	 * @param pageId
	 * @return
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * @throws ParserException
	 */
	public Page getPageByPageId(StringBuffer requestUrlSB, Integer pageId) {
		Page page = pageDao.selectByPrimaryKey(pageId);
		return page;
	}

	/**
	 * 判断pageId在数据库中是否存在
	 * 
	 * @param pageId
	 * @return
	 */
	public Boolean checkPageIdExist(Integer pageId) {
		return pageDao.checkPageIdExist(pageId);
	}

	/**
	 * 新增一条信息，只有 pageId
	 * 
	 * @param pageBean
	 */
	public void savePage(Page pageBean) {
		pageDao.insert(pageBean);
	}

}